package com.hctforgreen.greenservice;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.db.DBVideoDownloadManager;
import com.hctforgreen.greenservice.db.DBVideoManager;
import com.hctforgreen.greenservice.model.ResultEntity;
import com.hctforgreen.greenservice.model.VideoTypeEntity.VideoDetailEntity;
import com.hctforgreen.greenservice.model.VideoTypeEntity.VideoDetailEntity.VideoPartEntity;
import com.hctforgreen.greenservice.ui.adapter.VideoPartsAdapter;
import com.hctforgreen.greenservice.utils.AsyncImageLoader;
import com.hctforgreen.greenservice.utils.AsyncImageLoader.ImageCallback;
import com.hctforgreen.greenservice.utils.DownloadUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.ScreenUtil;
import com.hctforgreen.greenservice.utils.Utils;

import java.io.File;

/**
 * 视频详情页面(显示剧集)
 * 
 * @author denghb
 * 
 */
public class VideoPartsActivity extends ParentActivity {

	private VideoPartsAdapter mAdapter;
	private DownloadDownReceiver mUpdateReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_part_detail);
		initSkinLayout();
		initTitleButtonBar();
		initDownloadDownReceiver();
		initDataAndWindow();

	}

	private void initDataAndWindow() {
		final String videoId = getIntent().getStringExtra("videoId");
		final ImageView videoImg = (ImageView) findViewById(R.id.video_img);
		final TextView tvContent = (TextView) findViewById(R.id.tv_content);
		final GridView gridView = (GridView) findViewById(R.id.grid_parts);

		final View loadView = findViewById(R.id.lyt_load_view);
		final Handler handler = new Handler() {
			@Override
			public void dispatchMessage(Message msg) {
				switch (msg.what) {
				case HctConstants.STATUS_FAILD:

					break;
				case HctConstants.STATUS_SUCCESS:
					final VideoDetailEntity detailEntity = (VideoDetailEntity) ((HctResult) msg.obj).data;
					if (detailEntity != null) {

						tvContent.setText(Html.fromHtml(detailEntity.detail)
								.toString());
						if (detailEntity.partEntities != null
								&& !detailEntity.partEntities.isEmpty()) {
							/**
							 * 初始化下载按钮
							 */
							final Button btnRight = (Button) findViewById(R.id.btn_right);
							btnRight.setBackgroundResource(R.drawable.btn_video_downloader_selector);
							btnRight.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {

									new HandlerThread("start_download") {
										@Override
										public void run() {
											try {
												for (VideoPartEntity partEntity : detailEntity.partEntities) {
													partEntity.videoName = detailEntity.name;
												}
												DBVideoDownloadManager dbVideoDownloadManager = new DBVideoDownloadManager(
														getApplicationContext());
												dbVideoDownloadManager
														.add(detailEntity.partEntities);
											} catch (Exception e) {
												e.printStackTrace();
											}

											runOnUiThread(new Runnable() {
												public void run() {
													startActivity(new Intent(
															VideoPartsActivity.this,
															VideoDownloadActivity.class));
												}
											});
											super.run();
										}
									}.start();

								}
							});
							/**
							 * 加载图片
							 */
							AsyncImageLoader imageLoader = new AsyncImageLoader();
							Drawable bitmapDrawable = imageLoader.loadDrawable(
									detailEntity.partEntities.get(0).picUrl,
									getApplicationContext(), true,
									new ImageCallback() {

										@Override
										public void imageLoaded(
												Drawable imageDrawable,
												String imageUrl) {
											if (imageDrawable != null) {
												BitmapDrawable drawable = (BitmapDrawable) imageDrawable;
												Bitmap bitmap = drawable
														.getBitmap();
												if (bitmap != null) {
													ScreenUtil screenUtil = new ScreenUtil();
													int height = bitmap
															.getHeight()
															* screenUtil
																	.getScreenWidth(VideoPartsActivity.this)
															/ bitmap.getWidth();
													setLayoutHeightAndWidth(
															screenUtil
																	.getScreenWidth(VideoPartsActivity.this),
															height, videoImg);
												}
												videoImg.setImageDrawable(imageDrawable);
											}
										}
									});
							if (bitmapDrawable != null) {
								BitmapDrawable drawable = (BitmapDrawable) bitmapDrawable;

								Bitmap bitmap = drawable.getBitmap();
								if (bitmap != null) {
									ScreenUtil screenUtil = new ScreenUtil();
									int height = bitmap.getHeight()
											* screenUtil
													.getScreenWidth(VideoPartsActivity.this)
											/ bitmap.getWidth();
									setLayoutHeightAndWidth(
											screenUtil
													.getScreenWidth(VideoPartsActivity.this),
											height, videoImg);
								}

								videoImg.setImageDrawable(bitmapDrawable);
							} else {
								videoImg.setImageResource(R.drawable.ic_default_pic);
							}
							// 显示剧集
							mAdapter = new VideoPartsAdapter(
									getApplicationContext(),
									detailEntity.partEntities);
							gridView.setAdapter(mAdapter);
							gridView.setOnItemClickListener(new OnItemClickListener() {

								@Override
								public void onItemClick(AdapterView<?> arg0,
										View arg1, int position, long arg3) {
									playVideo(detailEntity,
											detailEntity.partEntities
													.get(position));
								}
							});
							// 添加播放按钮事件

							final ImageView btnPlay = (ImageView) findViewById(R.id.img_play_video);
							btnPlay.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									playVideo(detailEntity,
											detailEntity.partEntities.get(0));
								}
							});
						}
					}
					break;
				default:
					break;
				}

				loadView.setVisibility(View.GONE);
				super.dispatchMessage(msg);
			}
		};
		loadView.setVisibility(View.VISIBLE);
		new Thread() {
			public void run() {
				HctController hctController = new HctController(
						VideoPartsActivity.this);

				try {
					HctResult hctResult = hctController
							.getVideoDetailById(videoId);
					handler.sendMessage(handler.obtainMessage(
							HctConstants.STATUS_SUCCESS, hctResult));

				} catch (Exception e) {
					handler.sendEmptyMessage(HctConstants.STATUS_FAILD);
					e.printStackTrace();
				}

			};
		}.start();
	}

	private void playVideo(final VideoDetailEntity detailEntity,
			final VideoPartEntity partEntity) {

		final DBVideoDownloadManager downloadManager = new DBVideoDownloadManager(
				getApplicationContext());
		if (downloadManager.haveDownloadEntity(partEntity)) {
			partEntity.videoName = detailEntity.name;
			String fileName = VideoPartEntity.makeVideoFileName(partEntity,
					this);
			// 已下载
			if (fileName != null && new File(fileName).exists()) {// 文件存在

				insertDBAndAddCount(detailEntity, partEntity);
				new Handler().postDelayed(new Runnable() {// 不知道什么情况
							// 一定要延迟才能在第一次点击时播放

							@Override
							public void run() {
								// TODO Auto-generated method stub

								Intent intent = new Intent(Intent.ACTION_VIEW);
								// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								Uri uri = Uri.parse("file://"
										+ VideoPartEntity.makeVideoFileName(
												partEntity,
												VideoPartsActivity.this));
								intent.setDataAndType(uri, "video/*");
								startActivity(intent);
							}
						}, 20);
			} else {
				partEntity.downloadState = "";
				downloadManager.updatepartEntity(partEntity);
				if (mAdapter != null) {
					mAdapter.notifyDataSetChanged();
				}
				DownloadUtil downloadUtil = new DownloadUtil();
				downloadUtil.makeSureDownloadDiaolg(this, partEntity);
			}
		} else {
			if (!Utils.isWifiNetworkConnected(getApplicationContext())) {
				AlertDialog.Builder builder = new Builder(
						VideoPartsActivity.this);
				builder.setMessage(
						getString(R.string.video_dialog_network_3g_wran))
						.setTitle(getString(R.string.dialog_default_title_hint))
						.setNegativeButton(
								getString(R.string.dialog_cancel_hint), null)
						.setPositiveButton(
								getString(R.string.dialog_confirm_hint),
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										insertDBAndAddCount(detailEntity,
												partEntity);
										Intent intent = new Intent(
												Intent.ACTION_VIEW);
										Uri uri = Uri
												.parse(partEntity.videoUrl);
										intent.setDataAndType(uri, "video/*");
										intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										startActivity(intent);
									}
								}).create().show();
			} else {
				insertDBAndAddCount(detailEntity, partEntity);
				insertDBAndAddRecord(getApplicationContext(),partEntity.id);
				Intent intent = new Intent(Intent.ACTION_VIEW);
				Uri uri = Uri.parse(partEntity.videoUrl);
				intent.setDataAndType(uri, "video/*");
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			}
		}

	}
	private void insertDBAndAddRecord(final Context context, final String videoPartId){
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
					case HctConstants.STATUS_SUCCESS:

						hctResult = (HctResult) msg.obj;

						ResultEntity entity = (ResultEntity) hctResult.data;

						break;

					case HctConstants.STATUS_FAILD:

						break;
				}
			}

		};
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(context);

					HctResult result = controller.addVideoPlayRecord(videoPartId,
							LoginResultStoreUtil.get(context).personId);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();

	}
	private void insertDBAndAddCount(final VideoDetailEntity detailEntity,
			final VideoPartEntity partEntity) {
		new Thread() {
			public void run() {// 插入本地数据库，历史播放记录
				try {
					DBVideoManager dbVideoManager = new DBVideoManager(
							VideoPartsActivity.this);
					partEntity.videoName = detailEntity.name;
					dbVideoManager.add(partEntity);

					HctController controller = new HctController(
							VideoPartsActivity.this);
					controller.addVideoPalyCount(partEntity.id);// 增加统计
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();

	}


	private void initTitleButtonBar() {
		final String typeName = getIntent().getStringExtra("videoName");
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(typeName);

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	private void setLayoutHeightAndWidth(int weight, int height, View viewGroup) {
		LayoutParams gLayoutParams = viewGroup.getLayoutParams();
		if (weight != 0) {
			gLayoutParams.width = weight;
		}
		if (height != 0) {
			gLayoutParams.height = height;
		}
		viewGroup.setLayoutParams(gLayoutParams);
	}

	@Override
	protected void onDestroy() {
		if (mUpdateReceiver != null) {
			unregisterReceiver(mUpdateReceiver);
		}
		super.onDestroy();
	}

	/**
	 * 
	 * @author dhb
	 * 
	 */
	public class DownloadDownReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (mAdapter != null) {
				mAdapter.notifyDataSetChanged();
			}
		}
	}

	private void initDownloadDownReceiver() {
		/**
		 * 注册下载完成监听，刷新已下载数据
		 */
		mUpdateReceiver = new DownloadDownReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(HctConstants.RECEIVER_VIDEOSHELF_ACTIVITY_DOWNLOAD_UPDATE_PARTS);
		registerReceiver(mUpdateReceiver, filter);
	}

}
